package com.leetcodehot.problems;

public class problems938 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int rangeSumBST(TreeNode root, int low, int high) {
        return dfs(root,low,high);
    }

    private int dfs(TreeNode root, int low, int high) {
        if (root == null) return 0;
        int x = root.val;
        if(x<low){
            return dfs(root.right,low,high);
        }
        else if(x>high){
            return dfs(root.left,low,high);
        }else{
            int left = dfs(root.left,low,high);
            int right = dfs(root.right,low,high);
            return x + left + right;
        }
    }
}
